package com.stylefeng.guns.biz.api.task;

import java.util.Date;
import java.util.TimerTask;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.biz.data.model.TDataClick;
import com.stylefeng.guns.biz.data.service.ITDataClickService;
import com.stylefeng.guns.core.log.LogManager;
import com.stylefeng.guns.core.util.SpringContextHolder;

/**
 * 日志操作任务创建工厂
 *
 * @author sundm
 * @date 2016年12月6日 下午9:18:27
 */
public class TaskFactory {

    private static Logger logger = LoggerFactory.getLogger(LogManager.class);

    private static ITDataClickService dataClickService = SpringContextHolder.getBean(ITDataClickService.class);

    public static TimerTask saveClickData(final String appid,final String source,
    		final Integer jumpType,String customerAppId) {
        return new TimerTask() {
            @Override
            public void run() {
                try {
                	EntityWrapper<TDataClick> wrapper=new EntityWrapper<>();
            		
//                	wrapper.eq("type", type);
                	wrapper.eq("app_id", appid);
                	if(StringUtils.isNotBlank(source)) {
                		wrapper.eq("source", source);
                	}
                	if(StringUtils.isNotBlank(customerAppId)) {
                		wrapper.eq("customer_app_id", customerAppId);
                	}
                	/*if(null!=dataId) {
                    	wrapper.eq("data_id", dataId);
                	}*/
                	TDataClick model = dataClickService.selectOne(wrapper);
                	if(null==model) {
                		TDataClick click=new TDataClick();
                    	click.setAppId(appid);
//                    	click.setPage(page);
                    	click.setCustomerAppId(customerAppId);
                    	/*if(StringUtils.isNotBlank(type)){
                    		click.setType(Integer.valueOf(type));
                    	}*/
                    	click.setJumpType(jumpType);
                    	click.setSource(source);
                    	click.setUpdateTime(new Date());
                		click.setCreateTime(new Date());
                		click.setTotalCount(1l);
//                		click.setDataId(dataId);
                    	dataClickService.insert(click);
                	}else{
                		long totalCount = model.getTotalCount();
                		model.setTotalCount(totalCount+1);
                		model.setUpdateTime(new Date());
                		dataClickService.updateById(model);
                	}
                } catch (Exception e) {
                    logger.error("数据采集报错!", e);
                }
            }
        };
    }
}
